<template>
  <el-drawer v-model="drawerVisible" :z-index="1000" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}角色`">
    <el-form
      ref="roleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
      v-if="drawerProps.row"
    >
      <el-form-item label="角色ID" prop="roleid">
        <el-input v-model="drawerProps.row!.roleid" placeholder="请填写角色ID" clearable></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="rolename">
        <el-input v-model="drawerProps.row!.rolename" placeholder="请填写角色描述" clearable></el-input>
      </el-form-item>
      <el-form-item label="备注信息">
        <el-input v-model="drawerProps.row!.note" placeholder="备注信息" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="_colse">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="RoleDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";

interface DrawerProps {
  title: string;
  isView: boolean;
  row: {
    [key: string]: any;
  };
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
}

const loading = ref(false);
const drawerVisible = ref(false);

const rules = reactive({
  roleid: [{ required: true, trigger: "blur", message: "请填写角色ID" }],
  rolename: [{ required: true, trigger: "blur", message: "请填写角色描述" }]
});

const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  if (drawerProps.value.title !== "新增") {
  }
};

// 提交数据（新增/编辑）
const roleFormRef = ref<FormInstance>();

/**
 * 关闭抽屉
 */
const _colse = () => {
  drawerVisible.value = false;
  roleFormRef.value && roleFormRef.value.resetFields();
};

/**
 * 提交信息
 */
const handleSubmit = () => {
  roleFormRef.value!.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      await drawerProps.value.api!({ ...drawerProps.value.row });
      ElMessage.success({ message: `${drawerProps.value.title}角色成功！` });
      drawerProps.value.title === "新增" ? drawerProps.value.resetTableList!() : drawerProps.value.getTableList!();
      drawerVisible.value = false;
      loading.value = false;
    } catch (error) {
      loading.value = false;
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
